


<!DOCTYPE html>
<html lang="zh-CN">
  <head><meta name="generator" content="Hexo 3.8.0">
    <title>创建自定义滚动指令 — Vue.js</title>
    <meta charset="utf-8">
    <meta name="description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="alternate" hreflang="x-default" href="https://vuejs.org/v2/cookbook/creating-custom-scroll-directives.html">
    <link rel="alternate" hreflang="zh" href="creating-custom-scroll-directives.html">
    <link rel="alternate" hreflang="ja" href="https://jp.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html">
    <link rel="alternate" hreflang="ru" href="https://ru.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html">
    <link rel="alternate" hreflang="ko" href="https://kr.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html">
    <link rel="alternate" hreflang="pt-BR" href="https://br.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html">
    <link rel="alternate" hreflang="fr" href="https://fr.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html">

    <meta property="og:type" content="article">
    <meta property="og:title" content="创建自定义滚动指令 — Vue.js">
    <meta property="og:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta property="og:image" content="https://cn.vuejs.org//images/logo.png">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="创建自定义滚动指令 — Vue.js">
    <meta name="twitter:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="twitter:image" content="https://cn.vuejs.org/images/logo.png">

    <link rel="apple-touch-icon" sizes="57x57" href="../../images/icons/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="../../images/icons/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="../../images/icons/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="../../images/icons/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="../../images/icons/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="../../images/icons/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="../../images/icons/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="../../images/icons/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="../../images/icons/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="../../images/icons/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="../../images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="../../images/icons/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="../../images/icons/favicon-16x16.png">
    <meta name="msapplication-TileImage" content="/images/icons/ms-icon-144x144.png">
    <link rel="icon" href="../../images/logo.png" type="image/png">

    <meta name="msapplication-TileColor" content="#4fc08d">
    <meta name="theme-color" content="#4fc08d">

    <meta name="msapplication-config" content="browserconfig.xml">
    <link rel="manifest" href="../../manifest.json">

    <!-- <link href="https://fonts.googleapis.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com" rel="preconnect" crossorigin> -->

    <!-- <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono' rel='stylesheet' type='text/css'> -->
    <!-- <link href='//fonts.googleapis.com/css?family=Dosis:500&text=Vue.js' rel='stylesheet' type='text/css'> -->

    <link href="https://code.bdstatic.com/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- main page styles -->
    <link rel="stylesheet" href="../../css/page.css">

    <!-- this needs to be loaded before guide's inline scripts -->
    <script src="../../js/vue.js"></script>

    

    <script>
      Vue.config.productionTip = false
      window.PAGE_TYPE = "cookbook"
    </script>

    <!-- ga -->
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-46852172-3', 'cn.vuejs.org');
      ga('send', 'pageview');
    </script>
  </head>
  <body class="docs">
    <div id="mobile-bar">
      <a class="menu-button"></a>
      <a class="logo" href="../../index.html"></a>
    </div>
    <div id="header">
  <a id="logo" href="../../index.html">
    <img src="../../images/logo.png" alt="vue logo">
    <span>Vue.js</span>
  </a>
  <ul id="nav">
    <li>
  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input" aria-label="搜索">
  </form>
</li>
<li class="nav-dropdown-container learn">
  <a class="nav-link current">学习</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>文档</h4></li>
    <li>
      <ul>
        <li><a href="../guide/index.html" class="nav-link">教程</a></li>
        <li><a href="../api/index.html" class="nav-link">API</a></li>
        <li><a href="../style-guide/index.html" class="nav-link">风格指南</a></li>
        <li><a href="../examples/index.html" class="nav-link">示例</a></li>
        <li><a href="index.html" class="nav-link current">Cookbook</a></li>
      </ul>
    </li>
    <li><h4>视频教程</h4></li>
    <li>
      <ul>
        <li><a href="https://www.vuemastery.com/courses/" class="nav-link" target="_blank" rel="sponsored noopener">Vue Mastery (英文)</a></li>
        <li><a href="https://vueschool.io/?friend=vuejs&amp;utm_source=Vuejs.org&amp;utm_medium=Link&amp;utm_content=Navbar%20Dropdown" class="nav-link" target="_blank" rel="noopener">Vue School (英文)</a></li>
        <li><a href="https://learning.dcloud.io/" class="nav-link" target="_blank" rel="sponsored noopener">DCloud 视频教程</a></li>
      </ul>
    </li>
  </ul>
</li>

<li class="nav-dropdown-container ecosystem">
  <a class="nav-link">生态系统</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>帮助</h4></li>
    <li><ul>
      <li><a href="https://forum.vuejs.org/" class="nav-link" target="_blank" rel="noopener">论坛</a></li>
      <li><a href="https://chat.vuejs.org/" class="nav-link" target="_blank" rel="noopener">聊天室</a></li>
      <li><a href="https://events.vuejs.org/meetups/" class="nav-link" target="_blank" rel="noopener">聚会</a></li>
    </ul></li>
    <li><h4>工具</h4></li>
    <li>
      <ul>
        <li><a href="https://github.com/vuejs/vue-devtools" class="nav-link" target="_blank" rel="noopener">Devtools</a></li>
        <li><a href="https://cli.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue CLI</a></li>
        <li><a href="https://vue-loader.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Loader</a></li>
      </ul>
    </li>
    <li><h4>核心插件</h4></li>
    <li><ul>
      <li><a href="https://router.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Router</a></li>
      <li><a href="https://vuex.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vuex</a></li>
      <li><a href="https://ssr.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue 服务端渲染</a></li>
    </ul></li>
    <li><h4>信息</h4></li>
    <li><ul>
      <li><a href="https://news.vuejs.org" class="nav-link" target="_blank" rel="noopener">周刊</a></li>
      <li><a href="https://github.com/vuejs/vue/projects/6" class="nav-link" target="_blank" rel="noopener">Roadmap</a></li>
      <li><a href="https://events.vuejs.org/" class="nav-link" target="_blank" rel="noopener">活动</a></li>
      <li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank" rel="noopener">Twitter</a></li>
      <li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank" rel="noopener">博客</a></li>
      <li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank" rel="noopener">工作</a></li>
    </ul></li>
  </ul>
</li>

<li>
  <a href="../guide/team.html" class="nav-link team">团队</a>
</li>
<li class="nav-dropdown-container resources">
  <a href="#" class="nav-link">资源列表</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="../../resources/partners.html" class="nav-link">合作伙伴</a></li>
    <li><a href="../../resources/themes.html" class="nav-link">主题</a></li>
    <li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank">Awesome Vue</a></li>
  </ul>
</li>

<!-- <li>
  <a href="/partners" class="nav-link ">Partners</a>
</li> -->
<li class="nav-dropdown-container support-vue">
  <a href="../../support-vuejs/index.html" class="nav-link">支持 Vue</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="../../support-vuejs/index.html#One-time-Donations" class="nav-link">一次性赞助</a></li>
    <li><a href="../../support-vuejs/index.html#Recurring-Pledges" class="nav-link">周期性赞助</a></li>
    <li><a href="https://www.smallsticker.com/%E8%B4%B4%E7%BA%B8/vue.html" rel="noopener" class="nav-link">贴纸</a></li>
    <li><a href="https://osholic.com/?utm_source=vue&amp;utm_medium=dropdown" rel="noopener" class="nav-link">周边</a></li>
    <li><a href="https://vue.threadless.com" target="_blank" rel="noopener" class="nav-link">T 恤商店</a></li>
  </ul>
</li>

<li class="nav-dropdown-container language">
  <a class="nav-link">多语言</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://vuejs.org/v2/cookbook/creating-custom-scroll-directives.html" class="nav-link" target="_blank" rel="noopener">English</a></li>
    <li><a href="https://jp.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html" class="nav-link" target="_blank" rel="noopener">日本語</a></li>
    <li><a href="https://ru.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html" class="nav-link" target="_blank" rel="noopener">Русский</a></li>
    <li><a href="https://kr.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html" class="nav-link" target="_blank" rel="noopener">한국어</a></li>
    <li><a href="https://br.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html" class="nav-link" target="_blank" rel="noopener">Português</a></li>
    <li><a href="https://fr.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html" class="nav-link" target="_blank" rel="noopener">Français</a></li>
    <li><a href="https://vi.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html" class="nav-link" target="_blank" rel="noopener">Tiếng Việt</a></li>
  </ul>
</li>

<li><a href="https://github.com/vuejs/cn.vuejs.org/" target="_blank" class="nav-link contribute">参与翻译</a></li>

  </ul>
</div>

    
      <div id="main" class="fix-sidebar">
        
          
  

<div class="sidebar">
  <div class="sidebar-inner">
    
    <div class="list">
      <div id="sidebar-sponsors-special">
  <div class="main-sponsor">
    <span>特别赞助商</span>
    <div>
    <a href="http://www.dcloud.io/?hmsr=vuejsorg&amp;hmpl=&amp;hmcu=&amp;hmkw=&amp;hmci=" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/dcloud.gif" alt="">
    </a>
    </div>
    <div>
    <a href="https://youzan.github.io/vant?source=vuejsorg" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/vant.png" alt="">
    </a>
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-left">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->

      
        <h2>
          
          Cookbook<sup class="beta">beta</sup>
          
        </h2>
        <ul class="menu-root">
  
    
    
    <li>
      <a href="index.html" class="sidebar-link">介绍</a>
    </li>
  
    
    
    <li>
      <a href="adding-instance-properties.html" class="sidebar-link">添加实例属性</a>
    </li>
  
    
    
    <li>
      <a href="form-validation.html" class="sidebar-link">表单校验</a>
    </li>
  
    
    
    <li>
      <a href="editable-svg-icons.html" class="sidebar-link">可编辑的 SVG 图标系统</a>
    </li>
  
    
    
    <li>
      <a href="serverless-blog.html" class="sidebar-link">创建一个基于 CMS 的博客</a>
    </li>
  
    
    
    <li>
      <a href="unit-testing-vue-components.html" class="sidebar-link">Vue 组件的单元测试</a>
    </li>
  
    
    
    <li>
      <a href="creating-custom-scroll-directives.html" class="sidebar-link current">创建自定义滚动指令</a>
    </li>
  
    
    
    <li>
      <a href="debugging-in-vscode.html" class="sidebar-link">在 VS Code 中调试</a>
    </li>
  
    
    
    <li>
      <a href="using-axios-to-consume-apis.html" class="sidebar-link">使用 axios 访问 API</a>
    </li>
  
    
    
    <li>
      <a href="avoiding-memory-leaks.html" class="sidebar-link">避免内存泄漏</a>
    </li>
  
    
    
    <li>
      <a href="client-side-storage.html" class="sidebar-link">客户端存储</a>
    </li>
  
    
    
    <li>
      <a href="packaging-sfc-for-npm.html" class="sidebar-link">Packaging Vue Components for npm</a>
    </li>
  
    
    
    <li>
      <a href="dockerize-vuejs-app.html" class="sidebar-link">Dockerize Vue.js App</a>
    </li>
  
    
    
    <li>
      <a href="practical-use-of-scoped-slots.html" class="sidebar-link">Practical use of scoped slots with GoogleMaps</a>
    </li>
  
</ul>

      
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-right">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->


<div class="content cookbook with-sidebar ">
  
    
      
<div id="ad">
  <span style="float: right;">广告</span>
  <a href="https://time.geekbang.org/column/intro/216?code=mM%2FdqOPks0VQ7EkYGPNisoEpHDsb0ViHBXYa%2Fyg02k8%3D&amp;utm_term=SPoster" target="_blank" rel="sponsored noopener">
    <img src="../../images/geekbang-ad.jpg">
  </a>
  <!-- <a href="https://ke.qq.com/course/392130?saleToken=992600&from=pclink" target="_blank" rel="sponsored noopener">
    <img src="/images/tencent-ad.png">
  </a> -->
  <!-- <script
    async
    type="text/javascript"
    src="//cdn.carbonads.com/carbon.js?serve=CKYIK2QU&placement=vuejsorg"
    id="_carbonads_js">
  </script> -->
</div>


    
  
  
    <h1>创建自定义滚动指令</h1>
  

  <div class="ad-pagetop">
  <a href="http://www.tp-shop.cn/index.php?http_referer=vuejs" target="_blank" rel="noopener noreferrer">
    <span class="name">TPshop</span>
    <span class="description">中国免费商城系统 - 搜豹商城系统 - 免费50小时Vue视频教程</span>
    <span class="action">立即查看 &gt;</span>
  </a>
</div>


  
    <h2 id="基本的示例"><a href="#%E5%9F%BA%E6%9C%AC%E7%9A%84%E7%A4%BA%E4%BE%8B" class="headerlink" title="基本的示例"></a>基本的示例</h2><p>我们可能很多次想为网站的滚动事件添加一些行为，尤其是动画。已有的做法很多，但是代码和依赖最少的方式可能就是使用一个<a href="../guide/custom-directive.html">自定义指令</a>创建一个钩子，在特定的滚动事件之后作处理。</p>
<pre><code class="hljs js">Vue.directive(<span class="hljs-string">'scroll'</span>, &#123;
  <span class="hljs-attr">inserted</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el, binding</span>) </span>&#123;
    <span class="hljs-keyword">let</span> f = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">evt</span>) </span>&#123;
      <span class="hljs-keyword">if</span> (binding.value(evt, el)) &#123;
        <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">'scroll'</span>, f)
      &#125;
    &#125;
    <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'scroll'</span>, f)
  &#125;
&#125;)

<span class="hljs-comment">// main app</span>
<span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#app'</span>,
  <span class="hljs-attr">methods</span>: &#123;
    <span class="hljs-attr">handleScroll</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">evt, el</span>) </span>&#123;
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">window</span>.scrollY &gt; <span class="hljs-number">50</span>) &#123;
        el.setAttribute(
          <span class="hljs-string">'style'</span>,
          <span class="hljs-string">'opacity: 1; transform: translate3d(0, -10px, 0)'</span>
        )
      &#125;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">window</span>.scrollY &gt; <span class="hljs-number">100</span>
    &#125;
  &#125;
&#125;)</code></pre>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"centered"</span>&gt;</span>Scroll me<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
    <span class="hljs-attr">v-scroll</span>=<span class="hljs-string">"handleScroll"</span>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>
  &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A atque amet harum aut ab veritatis earum porro praesentium ut corporis. Quasi provident dolorem officia iure fugiat, eius mollitia sequi quisquam.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p class="tip">记住！指令必须在 Vue 实例之前注册好。</p>

<p>我们可能还需要一个样式属性来对中间值做过渡，在这个例子中：</p>
<pre><code class="hljs css"><span class="hljs-selector-class">.box</span> &#123;
  <span class="hljs-attribute">transition</span>: <span class="hljs-number">1.5s</span> all <span class="hljs-built_in">cubic-bezier</span>(0.39, 0.575, 0.565, 1);
&#125;</code></pre>
<p data-height="450" data-theme-id="5162" data-slug-hash="983220ed949ac670dff96bdcaf9d3338" data-default-tab="result" data-user="sdras" data-embed-version="2" data-pen-title="Custom Scroll Directive- CSS Transition" class="codepen">在 <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a> 查看 Sarah Drasner (<a href="https://codepen.io/sdras" target="_blank" rel="noopener">@sdras</a>) 的<a href="https://codepen.io/sdras/pen/983220ed949ac670dff96bdcaf9d3338/" target="_blank" rel="noopener">自定义滚动指令- CSS 过渡</a>。</p>

<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

<p>或者使用 GreenSock (GSAP) 或任何其它 JavaScript 动画库，代码会变得更加简洁：</p>
<pre><code class="hljs js">Vue.directive(<span class="hljs-string">'scroll'</span>, &#123;
  <span class="hljs-attr">inserted</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el, binding</span>) </span>&#123;
    <span class="hljs-keyword">let</span> f = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">evt</span>) </span>&#123;
      <span class="hljs-keyword">if</span> (binding.value(evt, el)) &#123;
        <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">'scroll'</span>, f)
      &#125;
    &#125;
    <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'scroll'</span>, f)
  &#125;
&#125;)

<span class="hljs-comment">// main app</span>
<span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#app'</span>,
  <span class="hljs-attr">methods</span>: &#123;
    <span class="hljs-attr">handleScroll</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">evt, el</span>) </span>&#123;
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">window</span>.scrollY &gt; <span class="hljs-number">50</span>) &#123;
        TweenMax.to(el, <span class="hljs-number">1.5</span>, &#123;
          <span class="hljs-attr">y</span>: <span class="hljs-number">-10</span>,
          <span class="hljs-attr">opacity</span>: <span class="hljs-number">1</span>,
          <span class="hljs-attr">ease</span>: Sine.easeOut
        &#125;)
      &#125;
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">window</span>.scrollY &gt; <span class="hljs-number">100</span>
    &#125;
  &#125;
&#125;)</code></pre>
<p>而且我们会从实现中移除之前的 CSS 过渡，因为 JavaScript 已经搞定了这件事。</p>
<h2 id="使用自定义指令的好处"><a href="#%E4%BD%BF%E7%94%A8%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%87%E4%BB%A4%E7%9A%84%E5%A5%BD%E5%A4%84" class="headerlink" title="使用自定义指令的好处"></a>使用自定义指令的好处</h2><p>Vue 为指令提供了丰富的选项，覆盖了绝大多数的常见用例，使得我们可以通过指令创建非常高效的开发体验。即便遇到了一个框架本身覆盖不到的极端情况，你也可以通过这种方式来解决，因为你可以很轻松地创建一个自定义指令来满足需求。</p>
<p>为元素附加或移除滚动事件是对于这项技术的一个很好的用例，因为就像其它我们使用的指令一样，它们有必要绑定在元素上，否则我们就需要寻找其 DOM 引用。这种模式避免了我们遍历 DOM 节点，保证事件的逻辑能够和需要引用的节点对应起来。</p>
<h2 id="真实的示例：为级联动画使用一个自定义滚动指令"><a href="#%E7%9C%9F%E5%AE%9E%E7%9A%84%E7%A4%BA%E4%BE%8B%EF%BC%9A%E4%B8%BA%E7%BA%A7%E8%81%94%E5%8A%A8%E7%94%BB%E4%BD%BF%E7%94%A8%E4%B8%80%E4%B8%AA%E8%87%AA%E5%AE%9A%E4%B9%89%E6%BB%9A%E5%8A%A8%E6%8C%87%E4%BB%A4" class="headerlink" title="真实的示例：为级联动画使用一个自定义滚动指令"></a>真实的示例：为级联动画使用一个自定义滚动指令</h2><p>在创建一个风格统一的网站的过程中，你可能会发现你在很多区域复用了相同类型的动画逻辑。看起来我们创建一个非常特殊的自定义指令很简单对吧？好，通常情况下如果你想复用它，那么你<em>只需</em>在每次使用的时候对其进行一些小的改动即可。</p>
<p>为了保持代码的精炼和易读，我们会传递一些预设参数，诸如我们向下滚动页面时动画的起始点和终止点。</p>
<p><strong>这个示例最好在<a href="https://s.codepen.io/sdras/debug/078c19f5b3ed7f7d28584da450296cd0" target="_blank" rel="noopener">全屏模式</a>下浏览。</strong></p>
<p></p><p data-height="500" data-theme-id="5162" data-slug-hash="c8c55e3e0bba997350551dd747119100" data-default-tab="result" data-user="sdras" data-embed-version="2" data-pen-title="Scrolling Example- Using Custom Directives in Vue" class="codepen">在 <a href="https://codepen.io" target="_blank" rel="noopener">CodePen</a> 查看 Sarah Drasner (<a href="https://codepen.io/sdras" target="_blank" rel="noopener">@sdras</a>) 的 <a href="https://codepen.io/sdras/pen/c8c55e3e0bba997350551dd747119100/" target="_blank" rel="noopener">滚动示例 - 在Vue中使用自定义指令&lt;/a。&gt;</a></p><p></p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

<p>在上述 demo 中，每个章节都有两个由滚动触发的不同类型的动画开关：一个渐变动画和一个动态改变 SVG 独立路径的动画。我们想要复用这两种动画，因此可以为每种动画各创建一个自定义指令。传入的参数将会帮助我们让一切都简单可复用。</p>
<p>为了展示实现方式，我们将会看一下这个渐变图形的示例，这里我们需要明确起始状态和完成状态，同时传入一个我们将要创建的渐变的路径的值。每个这样的参数都会以 <code>binding.value.foo</code> 的形式定义：</p>
<pre><code class="hljs js">Vue.directive(<span class="hljs-string">'clipscroll'</span>, &#123;
  <span class="hljs-attr">inserted</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el, binding</span>) </span>&#123;
    <span class="hljs-keyword">let</span> f = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">evt</span>) </span>&#123;
      <span class="hljs-keyword">var</span> hasRun = <span class="hljs-literal">false</span>
      <span class="hljs-keyword">if</span> (!hasRun &amp;&amp; <span class="hljs-built_in">window</span>.scrollY &gt; binding.value.start) &#123;
        hasRun = <span class="hljs-literal">true</span>
        TweenMax.to(el, <span class="hljs-number">2</span>, &#123;
          <span class="hljs-attr">morphSVG</span>: binding.value.toPath,
          <span class="hljs-attr">ease</span>: Sine.easeIn
        &#125;)
      &#125;
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">window</span>.scrollY &gt; binding.value.end) &#123;
        <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">'scroll'</span>, f)
      &#125;
    &#125;
    <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'scroll'</span>, f)
  &#125;
&#125;)</code></pre>
<p>然后我们可以在我们的模板中使用这个动画，在本例中我们会将该指令附加到一个 <code>clipPath</code> 元素上，然后将所有的参数放入一个对象传递到这个指令中。</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">clipPath</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"clip-path"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">path</span>
    <span class="hljs-attr">v-clipscroll</span>=<span class="hljs-string">"&#123; start: '50', end: '100', toPath: 'M0.39 0.34H15.99V22.44H0.39z' &#125;"</span>
    <span class="hljs-attr">id</span>=<span class="hljs-string">"poly-shapemorph"</span>
    <span class="hljs-attr">d</span>=<span class="hljs-string">"M12.46 20.76L7.34 22.04 3.67 18.25 5.12 13.18 10.24 11.9 13.91 15.69 12.46 20.76z"</span>
  /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">clipPath</span>&gt;</span></code></pre>
<h2 id="替代模式"><a href="#%E6%9B%BF%E4%BB%A3%E6%A8%A1%E5%BC%8F" class="headerlink" title="替代模式"></a>替代模式</h2><p>自定义指令是非常有用的，但是有时候你需要的一些特定逻辑，它们已经存在于一个滚动库里了，而你并不希望从零开始重构它。</p>
<p><a href="http://scrollmagic.io/" target="_blank" rel="noopener">Scrollmagic</a> 拥有一个非常丰富的生态系统，同时附带了很好的文档和演示以便大家浏览。这些特效包括且不仅限于诸如<a href="http://scrollmagic.io/examples/advanced/parallax_scrolling.html" target="_blank" rel="noopener">视差滚动</a>、<a href="http://scrollmagic.io/examples/expert/cascading_pins.html" target="_blank" rel="noopener">级联固定</a>、<a href="http://scrollmagic.io/examples/basic/section_wipes_natural.html" target="_blank" rel="noopener">章节切换</a>和<a href="http://scrollmagic.io/examples/basic/responsive_duration.html" target="_blank" rel="noopener">响应式持续时间</a>等。</p>

  
  
  <div class="footer">
      <script src="https://m.servedby-buysellads.com/monetization.js" type="text/javascript"></script>
<div id="bsa-native"></div>
<script>
_bsa.init('custom', 'CKYD62QM', 'placement:vuejsorg',
  {
    target: '#bsa-native',
    template: '<a class="native-box" href="##statlink##"><div class="native-sponsor">Sponsor</div><div class="native-text"><strong>##company##</strong> — ##description##</div></a>'
  }
);
</script>


    发现错误？想参与编辑？
    <a href="https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/cookbook/creating-custom-scroll-directives.md" rel="noopener" target="_blank">
      在 GitHub 上编辑此页！
    </a>
  </div>
</div>

        
      </div>
      <script src="../../js/smooth-scroll.min.js"></script>
    

    <!-- main custom script for sidebars, version selects etc. -->
    <script src="../../js/css.escape.js"></script>
    <script src="../../js/common.js"></script>

    <!-- search -->
    <link href="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="../../css/search.css">
    <script src="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.js"></script>
    <script>
    [
      '#search-query-nav',
      '#search-query-sidebar',
      '#search-query-menu'
    ].forEach(function (selector) {
      if (!document.querySelector(selector)) return
      // search index defaults to v2
      var match = window.location.pathname.match(/^\/(v\d+)/)
      var version = match ? match[1] : 'v2'
      docsearch({
      appId: 'BH4D9OD16A',
      apiKey: '5638280abff9d207417bb03be05f0b25',
      indexName: 'vuejs_cn2',
      inputSelector: selector,
      algoliaOptions: { facetFilters: ["version:" + version] },
      autocompleteOptions: { hint: false, appendTo: 'body'}
      })
    })
    </script>
  </body>
</html>
